const {resolve} = require('path')
const fs = require('fs')
const express = require('express')
const router = express.Router()

const resImgPath = 'http://127.0.0.1:8848/images/'

router.post('/', (req, res)=>{
    const {mimetype, destination, filename} = req.files[0]
    const imgrex = /.*?\/(png|jpe?g|gif)$/
    const prvePath = `../${destination}/${filename}`

    if (imgrex.test(mimetype)) {

        const type = mimetype.replace(imgrex, '$1')
        const imgname = `${filename}.${type}`
        const newimgPath = `../${destination}/${imgname}`
        fs.renameSync(resolve(__dirname, prvePath), resolve(__dirname, newimgPath))
        res.json({
            codo: 1,
            msg: 'upload ok',
            filepath: resImgPath + imgname
        })

    } else {
        fs.unlinkSync(prvePath)
        res.json({
            code: 0,
            msg: '请上传图片文件'
        })
    }
})

module.exports = router